﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;
using System.Data.Common;

namespace DAO.Common
{
    public static class DBHelper
    {

        public static DbConnection CreateDBConnection(string provider, string connstr) 
        {
            DbProviderFactory factory = DbProviderFactories.GetFactory(provider);
            DbConnection conn = factory.CreateConnection();
            conn.ConnectionString = connstr;

            return conn;
        }

        public static DbCommand CreateCommand(DbConnection conn, String commandText, CommandType cmdType)
        {
            //DbCommand command = factory.CreateCommand();
            DbCommand command = conn.CreateCommand();
            command.CommandText = commandText;
            command.CommandType = cmdType;
            command.Connection = conn;

            return command;
        }

        public static DbParameter CreateParameter(DbCommand command, ParameterHelper parameterHelper)
        {
            //DbParameter param = factory.CreateParameter();
            DbParameter param = command.CreateParameter();
            param.ParameterName = parameterHelper.Name;
            param.Value = parameterHelper.Value;
            param.DbType = parameterHelper.DbType;
            param.Direction = parameterHelper.Direction;

            command.Parameters.Add(param);

            return param;
        }

        public static void CreateParameters(DbCommand command, List<ParameterHelper> paramHelpers) 
        {
            if(paramHelpers != null)
                foreach (ParameterHelper param in paramHelpers)
                    CreateParameter(command, param);
        }

        public static DbCommand CreateCommandWithParameters(
            DbConnection conn, string commandText,
            CommandType cmdType, List<ParameterHelper> paramHelpers) 
        {
            DbCommand command = CreateCommand(conn, commandText, cmdType);
            CreateParameters(command, paramHelpers);

            return command;
        }
    }
}
